package com.leetcode.LC_MED;

import java.util.TreeMap;

public class LC57 {
    public int[][] insert(int[][] intervals, int[] newInterval) {

        //思路利用TreeMap排序去重，然后提取同一区间最大结尾，很暴力
        if (intervals.length == 0) {
            return new int[][]{{newInterval[0], newInterval[1]}};
        }
        TreeMap<Integer, Integer> map = new TreeMap<>();
        boolean tmp = false;
        int a = 0;

        map.put(newInterval[0], newInterval[1]);
        for (int[] interval : intervals) {
            if (map.containsKey(interval[0])) {
                map.put(interval[0], Math.max(interval[1], map.get(interval[0])));
            } else {
                map.put(interval[0], interval[1]);
            }
        }
        int k = 0;
        int[][] ints1 = new int[intervals.length + 1][2];
        for (Integer integer : map.keySet()) {
            ints1[k][0] = integer;
            ints1[k][1] = map.get(integer);
            k++;
        }

        for (Integer integer : map.keySet()) {
            System.out.println(integer + ":" + map.get(integer));
        }
        map.clear();

        int max = -1;
        for (int i = 0; i < ints1.length; i++) {
            if (!tmp) {
                a = ints1[i][0];
                max = ints1[i][1];
                tmp = true;
            }
            if (i + 1 < ints1.length && max >= ints1[i + 1][0] /*&&intervals[i][1] <= intervals[i + 1][1]*/) {
                max = Math.max(max, ints1[i + 1][1]);
            } else {
                tmp = false;
                map.put(a, max);
                max = -1;
            }
        }
        for (Integer integer : map.keySet()) {
            System.out.println(integer + ":" + map.get(integer));
        }

        int[][] ints = new int[map.size()][2];
        k = 0;
        for (Integer integer : map.keySet()) {
            ints[k][0] = integer;
            ints[k][1] = map.get(integer);
            k++;
        }
        return ints;

    }
}
